/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
<div>
  <div v-if="flag === 1" class="login-container" style="border: 0px solid red;">
    <el-form class="login-form" auto-complete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left">
      <h3 class="title">{{title }}</h3>
      <el-form-item prop="user_name">
        <span class="svg-container svg-container_login">
          <svg-icon icon-class="user" />
        </span>
        <el-input class="login-input" name="user_name" type="text" v-model="loginForm.user_name" auto-complete="on" :placeholder="$t('openatc.login.username')" />
      </el-form-item>
      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password"></svg-icon>
        </span>
        <el-input class="login-input" name="password" :type="pwdType" @keyup.enter.native="handleLogin" v-model="loginForm.password" auto-complete="on"
          :placeholder="$t('openatc.login.password')"></el-input>
          <span class="show-pwd" @click="showPwd">
             <svg-icon :icon-class="pwdType === 'password' ? 'eye' : 'eye-open'" />
          </span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width:100%;" :loading="loading" @click.native.prevent="handleLogin">
          {{$t('openatc.login.login')}}
        </el-button>
      </el-form-item>
    </el-form>
    <!--修改密码弹框-->
  </div>
  <div v-if="flag === 2" style="border:0px solid green;width:100%;height:10%;margin-bottom:0px;display:flex;justify-content:flex-end;">
    <div style="border:0px solid red;width:120px;height:100%;display:flex;justify-content:space-around;align-items:center;margin-top:18px;">
      <div class="isopen" style="border:0px solid red;font-size:14px;">
        <el-switch
          style="padding-left: 5px;"
          v-model="isOpen"
          :active-value="true"
          :inactive-value="false"
          @change="onSwitchChange"
          :active-text="$t('openatc.main.dark')"
          active-color="#409EFF">
        </el-switch>
        <span style="margin-left:5px;">
          <!-- {{$t('openatc.main.dark')}} -->
        </span>
      </div>
    </div>
    <div style="border:0px solid yellow;width:140px;height:100%;display:flex;justify-content:center;aligin-items:center;line-height:5px;">
      <div style="border:0px solid yellow;margin-top:10px;">
        <el-dropdown-item command="switchTheme">
          <el-dropdown trigger="click" @command="switchLanguage">
            <span class="el-dropdown-link">
              {{ languageText}}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="Ch">中文</el-dropdown-item>
              <el-dropdown-item command="En">English</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-dropdown-item>
      </div>
    </div>
  </div>
  <div v-if="flag === 2" class="modify-container" style="position: fixed;height: 90%;width: 100%;display:flex;justify-content:center;align-items:center;border: 0px solid red;">
    <div  class="modify-passwd" style="border: 0px solid yellow;width:600px;">
      <h3 class="title">{{title }}</h3>
      <el-form
        class="dialog-footer"
        ref="tempPassword"
        :model="PasswordData"
        :rules="rules"
        label-position="right"
        label-width="auto"
        style='width: 84%;border:0px solid red;margin-top: -20px;'
      >
        <el-form-item
          label=""
          prop="pass"
        >
          <!-- <el-button icon="el-icon-plus" class="subtitle" type="text">{{$t('openatc.login.createAdmin')}}</el-button> -->
        </el-form-item>
        <el-form-item
          :label="$t('openatc.login.username')"
          prop="pass"
        >
          <el-input
            :disabled="true"
            v-model="PasswordData.user_name"
          >
          </el-input>
        </el-form-item>
        <div class = "passCheck">
          <passCheck
            ref="checkPass"
            :newpassdata="PasswordData.newpass"
            @updateData="updatePassData"
          ></passCheck>
        </div>
        <el-form-item
          :label="$t('edge.auth.confirm')"
          prop="checknewpass"
        >
          <el-input
            type="password"
            v-model="PasswordData.checknewpass"
            placeholder=""
            onpaste="return false" oncontextmenu="return false" oncopy="return false" oncut="return false"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-plus" type="primary" style="width:100%;" :loading="loading" @click.native.prevent="onCreatClick">
            {{$t('openatc.login.createAdmin')}}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  <changePass ref="changepassChild" @onGetStatus="onGetStatus"></changePass>
</div>
</template>

<script>
import passCheck from '../compose/components/passwordCheck.vue'
import changePass from '../compose/components/ChangePass'
import { login, getInfo } from '../../api/login'
import Cookies from 'js-cookie'
import { GetUsrPermissions } from '../../api/user'
import { SetSimuUserKey, setLanguage, getLanguage, getTheme, setTheme, setPermissions, setUserRoles } from '../../utils/auth'
import { SystemconfigApi } from '../../api/systemconfig.js'
import { getMessageByCode } from '../../utils/responseMessage'
// import axios from 'axios'
import { clearCrossFilter } from '../../utils/crossFilterMgr'
import { HandleMenuVisible } from '../../utils/menuControl'

export default {
  name: 'login',
  components: {
    passCheck,
    changePass
  },
  props: {
    loginInterface: {
      type: Object
    }
  },
  data () {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('edge.auth.inputpassagain')))
      } else if (value !== this.PasswordData.newpass) {
        callback(new Error(this.$t('edge.auth.twopassinconsistent')))
      } else {
        callback()
      }
    }
    return {
      languageText: '语言',
      isOpen: true,
      flag: -1,
      title: 'OpenATC-Admin',
      loginForm: {
        user_name: '',
        password: '',
        vcode: '',
        vcodeKey: ''
      },
      loginRules: {
        user_name: [
          { required: true, trigger: 'blur', message: this.$t('openatc.login.usernamenotnull') }
        ],
        password: [
          { required: true, trigger: 'blur', message: this.$t('openatc.login.passnotnull') }
        ],
        vcode: [{ required: true, trigger: 'blur', message: 'Invalid VCode' }]
      },
      loading: false,
      pwdType: 'password',
      vcodeEnable: false,
      language: 'Language',
      user_name: '',
      PasswordData: {
        user_name: 'admin',
        pass: '',
        newpass: '',
        checknewpass: ''
      },
      rules: {
        pass: [{ required: true, message: this.$t('edge.auth.enterpass') }],
        newpass: [{ required: true, message: this.$t('edge.auth.enternewpass') }],
        checknewpass: [
          {
            required: true,
            validator: validatePass2,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.languageText = getLanguage() !== 'en' ? 'Language' : '语言'
    this.title = this.loginInterface.getLoginTitle()
    let theme = getTheme()
    this.isOpen = theme === 'dark'
    if (!theme) {
      // set light
      this.switchToLight()
    }
    // if (getHost() === null || getHost() === undefined || getHost() === '') {
    //   axios.get('./servConfig.json').then(val => {
    //     let str = val.data.servIp
    //     if (str === undefined || str === null) {
    //       setHost('')
    //     }
    //     setHost(str)
    //   })
    // }
  },
  methods: {
    onSwitchChange (val) {
      if (val) {
        this.switchToDark()
      } else {
        this.switchToLight()
      }
    },
    handleCommand (command) {
      switch (command) {
        case 'switchTheme':
          break
        case 'switchLanguage':
          break
        default: this.$route.push({ path: '/' })
      }
    },
    switchTheme (command) {
      switch (command) {
        case 'dark':
          this.switchToDark()
          break
        case 'light':
          this.switchToLight()
          break
        default:
          console.log(command)
          break
      }
    },
    onCreatClick () {
      let passwordCheck = this.$refs.checkPass
      let state = passwordCheck.checkNewPass()
      if (!state) {
        return
      }
      let changepassChild = this.$refs.changepassChild
      changepassChild.updateUser(this.PasswordData, false)
    },
    updatePassData (pass) {
      this.PasswordData.newpass = pass
    },
    onGetStatus (isFirstTime, language) {
      if (isFirstTime) {
        this.flag = 2
        if (getLanguage() === '') {
          setLanguage(language)
        }
      } else {
        this.flag = 1
      }
    },
    getInfo () {
      getInfo().then(data => {
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.userInfo = data.data.data
        let roleNames = this.userInfo.roleNames
        let userName = this.userInfo.user_name
        setUserRoles(roleNames)
        this.getUsrPermissions(userName)
      })
    },
    getUsrPermissions (userName) {
      GetUsrPermissions(userName).then(data => {
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        let permissions = data.data.data
        let permissionList = permissions.map(item => {
          return item.permission_code
        })
        // set cache
        setPermissions(permissionList)
      })
    },
    showPwd () {
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },
    handleLogin () {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          login(
            this.loginForm.user_name,
            this.loginForm.password,
            this.loginForm.vcodeKey,
            this.loginForm.vcode
          )
            .then(data => {
              if (data.data.success !== true) {
                if (data.data.code === '3009') {
                  this.$message.error(this.$t('openatc.login.passerror'))
                  this.loading = false
                  return
                }
                if (data.data.code === '3001') {
                  this.$message.error(this.$t('openatc.login.usernamenotexist'))
                  this.loading = false
                  return
                }
                this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
                this.loading = false
                return
              }
              this.loading = false
              SetSimuUserKey(this.loginForm.user_name)
              this.loginInterface.loginSucess(data.data.data.token)
              Cookies.set('singleToken', data.data.data.token)
              this.loadDefaultConfig()
              clearCrossFilter() // 清除路口管理过滤条件
            })
            .catch(err => {
              this.loading = false
              this.$message.error(err)
              this.loginInterface.loginFailed(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    loadLanguageConfig () {
      // 从接口获取默认语言并设置
      let reqData = {
        module: 'language',
        isValid: true
      }
      SystemconfigApi.GetSystemconfigList(reqData).then((data) => {
        let res = data.data
        if (!res.success) {
          throw new Error('get language error')
        } else {
          setLanguage(this.$i18n.locale)
          for (let config of data.data.data) {
            if (config['value'] === 'zh') {
              this.$i18n.locale = 'zh'
            } else if (config['value'] === 'en') {
              this.$i18n.locale = 'en'
            } else {
              this.setLanguageFromStorage()
            }
            setLanguage(this.$i18n.locale)
          }
        }
      })
    },
    setLanguageFromStorage () {
      // 从浏览器存储中读取语言配置
      let language = getLanguage()
      if (language === 'zh') {
        this.$i18n.locale = 'zh'
      } else if (language === 'en') {
        this.$i18n.locale = 'en'
      }
    },
    loadThemeConfig () {
      // 从接口获取默认皮肤并设置
      SystemconfigApi.GetSystemconfigByModule('theme').then((data) => {
        let res = data.data
        if (!res.success) {
          throw new Error('get theme error')
        } else {
          for (let config of data.data.data) {
            if (config['value'] === 'dark') {
              setTheme('dark')
              require('../../styles/dark/index.scss')
            } else if (config['value'] === 'light') {
              setTheme('light')
              require('../../styles/light/index.scss')
            }
          }
        }
      })
    },
    loadMenuConfig () {
      // 从接口获取是否显示地图菜单（可扩展为其他菜单是否显示）
      SystemconfigApi.GetSystemconfigByModule('gis').then((data) => {
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        HandleMenuVisible(data.data.data)
      })
      // set cache
      this.getInfo()
    },
    loadDefaultConfig  () {
      // 加载系统默认配置
      this.loadLanguageConfig()
      this.loadThemeConfig()
      this.loadMenuConfig()
    },
    switchLanguage (command) {
      switch (command) {
        case 'Ch':
          this.switchToChinese()
          break
        case 'En':
          this.switchToEngLish()
          break
        default:
          console.log(command)
          break
      }
    },
    switchToDark () {
      setTheme('dark')
      location.reload()
    },
    switchToLight () {
      setTheme('light')
      location.reload()
    },
    switchToChinese () {
      this.$i18n.locale = 'zh'
      setLanguage(this.$i18n.locale)
      location.reload()
    },
    switchToEngLish () {
      this.$i18n.locale = 'en'
      setLanguage(this.$i18n.locale)
      location.reload()
    }
  }
}
</script>

<style lang="scss">
</style>
